/*******************************************************************************
* 
* File system utility
*
* 
******************************************************************************/
#include "file-helper.h"
#include <iostream>
#include <fstream>

#include "logging.h"

using namespace std;
using namespace noria::diagnostic;

namespace noria{ namespace io
{
    size_t FileHelper::getFileLength(const wstring& path)
    {
        ifstream is;

        is.open(path, ios::binary);
        if(is.bad())
        {
            LOG_ERROR(L"Failure opening file, s=%s", path);
            return 0;
        }

        auto size = getFileLength(is);

        is.close();
        return size;
    }

    size_t FileHelper::getFileLength(const string& path)
    {
        ifstream is;

        is.open(path, ios::binary);
        if(is.bad())
        {
            LOG_ERROR("Failure opening file, s=%s", path);
            return 0;
        }

        auto size = getFileLength(is);

        is.close();
        return size;
    }

    size_t FileHelper::getFileLength(istream& s)
    {
        // get length of the input file:
        s.seekg (0, ios::end);
        auto ilen = s.tellg();
        s.seekg (0, ios::beg);

        return ilen;
    }

    binary_sp FileHelper::readAll(const wstring& path)
    {
        ifstream is;

        is.open(path, ios::binary);
        if(is.bad())
        {
            LOG_ERROR(L"Failure opening file, s=%s", path);
            return 0;
        }

        auto data = readAll(is);

        is.close();
        return data;
    }

    string FileHelper::readText(const wstring& path)
    {
        ifstream is;

        is.open(path, ios::binary);
        if(is.bad())
        {
            LOG_ERROR("Failure opening file, s=%s", path);
            return 0;
        }

        auto size = getFileLength(is);
        string buffer(size, 0);

        is.read(&buffer[0], size);

        is.close();

        return buffer;
    }

    binary_sp FileHelper::readAll(const string& path)
    {
        ifstream is;

        is.open(path, ios::binary);
        if(is.bad())
        {
            LOG_ERROR(L"Failure opening file, s=%s", path);
            return 0;
        }

        auto data = readAll(is);

        is.close();
        return data;
    }

    binary_sp FileHelper::readAll(istream& s)
    {
        auto ilen = getFileLength(s);
        binary_sp data(new binary(ilen));

        s.read((char*)&(*data.get())[0], ilen);

        return data;
    }
}}